package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.BrandCount;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface BrandCountRepository extends JpaRepository<BrandCount, Long> {

    @Query("select b from BrandCount b order by b.totalCount desc")
    List<BrandCount> findTopBrands(PageRequest pageable);

    default List<BrandCount> findTopBrands(int limit) {
        return findTopBrands(PageRequest.of(0, limit));
    }

    @Modifying
    @Transactional
    @Query(value = """
            insert into brand_count (brand, total_count)
            values (:brand, 1)
            on conflict (brand)
            do update set total_count = brand_count.total_count + 1
            """, nativeQuery = true)
    void upsertBrand(String brand);
}
